﻿using System;
using System.Collections;
using System.ComponentModel.Design;
using System.Reflection;

namespace GlobalizationTools.Model
{
    public class AssemblyNamesTypeResolutionService : ITypeResolutionService
    {
        // Fields
        private Hashtable cachedAssemblies;

        // Methods
        internal AssemblyNamesTypeResolutionService()
        {
        }

        public Assembly GetAssembly(AssemblyName name)
        {
            return this.GetAssembly(name, true);
        }

        public Assembly GetAssembly(AssemblyName name, bool throwOnError)
        {
            Assembly assembly = null;
            if (this.cachedAssemblies == null)
            {
                this.cachedAssemblies = new Hashtable();
            }
            if (this.cachedAssemblies.Contains(name))
            {
                assembly = this.cachedAssemblies[name] as Assembly;
            }
            if (assembly == null)
            {
                assembly = Assembly.Load(name.FullName);
                if (assembly != null)
                {
                    this.cachedAssemblies[name] = assembly;
                }
            }
            return assembly;
        }

        public string GetPathOfAssembly(AssemblyName name)
        {
            return name.CodeBase;
        }

        public Type GetType(string name)
        {
            return this.GetType(name, true);
        }

        public Type GetType(string name, bool throwOnError)
        {
            return this.GetType(name, throwOnError, false);
        }

        public Type GetType(string name, bool throwOnError, bool ignoreCase)
        {
            Type type = null;
            if (name.IndexOf(',') != -1)
            {
                type = Type.GetType(name, false, ignoreCase);
            }
            if ((type == null) && throwOnError)
            {
                throw new ArgumentException(string.Format("InvalidResXNoType {0}", new object[] { name }));
            }
            return type;
        }

        public void ReferenceAssembly(AssemblyName name)
        {
            throw new NotSupportedException();
        }
    }

}
